using System.Text;
using System.IO;
using System.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;

public abstract class ClassLoader {

    public StringBuilder builderSql=new StringBuilder();
    public ClassLoader(HashSet<Type> types,String baseName,String connStr)
    {           
     
        //设置一下数据库的链接
        SqlConFactory.SetConnection(connStr);

       
        builderSql.Append($"create database {baseName};");
        builderSql.Append($" use {baseName};");
            
        foreach(Type t in types){    
            BuildTable(t);
        }
    }
    public void BuildTable(Type t){
        string tableName=GetTableName(Attribute.GetCustomAttributes(t));
        if(tableName=="")return;
        builderSql.Append($" create table {tableName} ");
        builderSql.Append("(");
        FieldInfo[] fields= t.GetFields();
        foreach(FieldInfo info in fields){ 
            
           (bool IsNull,string columName,string types) r= IsNullAndGetval(info);
           
           builderSql.Append($"{r.columName} {r.types}");
           
           if(!r.IsNull)builderSql.Append($" not null");
            builderSql.Append(",");
        }
        builderSql.Remove(builderSql.Length-1,1);
        
        builderSql.Append(")");
        builderSql.Append("ENGINE=InnoDB DEFAULT CHARSET=utf8;");

    }
   public void Build(){
       MysqlHerper herper=MysqlHerper.getHerper();
       
       System.Console.WriteLine(builderSql.ToString());
       herper.Exquery(builderSql.ToString());
       System.Console.WriteLine("执行完毕！！！");
   }
    public (bool IsNull,string columName,string types) IsNullAndGetval(FieldInfo t){
        (bool IsNull,string columName,string types) res=(false,"","");
        if (t.GetCustomAttribute(typeof(NotNullAtter))!=null)
            res.IsNull=false;
        
        ColumAtter Colatter= (ColumAtter)t.GetCustomAttribute(typeof(ColumAtter));
        
        res.columName=Colatter.getColumName();
        
        res.types=Colatter.getTypes();
        return res;
    }
    

    public string GetTableName(System.Attribute[] attributes){
        foreach(Attribute atter in attributes){
            if(atter is TableAttr){
                return ((TableAttr)atter).getName();
            }
        }
        return "";
    }
}